import React from 'react'
import { Input,Button,Spin} from 'antd';
import * as conf from './config';

class App extends React.Component {

  /**
   * 设置初始值
   * @param props
   */
  constructor(props){
    super(props);
    this.state={
      loading: false,
      data:[],
      table:'m1c',
    }
  }

  /**
   * 第一次渲染后执行
   */
  componentDidMount() {
    this.find();
  }

  /**
   * 查找数据
   */
  find=()=>{
    conf.request(conf.action.find,{
      table:this.state.table,
      where:{_id:this.props.params.id}
    }).then((result) => {
      // console.log(result);
      this.setState({
        data:result.data
      })
    });
  };

  /**
   * 提交修改
   */
  submit=()=>{
    let params = {
      table:this.state.table,
      where:{_id:this.props.params.id},
      name:$('#name').val(),
    };
    if($.isEmptyObject(params.name)){
      conf.tips('error','操作失败!','字段不能为空');
    }else{
      this.update(params);
    }
  };

  /**
   * 更新
   * @param params
   */
  update=(params={})=>{
    this.setState({ loading: true });
    conf.request(conf.action.update,params).then((result)=>{
      // console.log(result);
      conf.tips(result);
      this.setState({
        loading: false,
      });
      this.find();
    })
  };

  /**
   * 文本框onchange事件
   * @param e
   */
  onChange = (e) => {
    let data = this.state.data;
    let self = e.target;
    let id = self.id; //获取id
    data[`${id}`] = self.value; //获取value
    this.setState({
      data:data
    });
  };

  /**
   * 渲染模版
   * @returns {XML}
   */
  render() {
    const data = this.state.data;
    return (
      <Spin spinning={this.state.loading} tip="Loading...">
        <div id="add">
          <div className="row">
            <Input id="name" value={data.name} onChange={this.onChange}/>
          </div>
          <div className="row">
            <Button type='primary' onClick={this.submit}>立即修改</Button>
          </div>
        </div>
      </Spin>
    );
  }
}


export default App